package com.whfc.openapi.api.hdc.service;

import com.whfc.common.constant.QueueConst;
import com.whfc.common.exception.BizException;
import com.whfc.common.file.FileHandler;
import com.whfc.common.file.FilePathConfig;
import com.whfc.common.push.*;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.tencent.TrtcApi;
import com.whfc.common.tencent.TrtcProperties;
import com.whfc.common.util.JSONUtil;
import com.whfc.common.util.RandomUtil;
import com.whfc.hdc.dto.FshDeviceConfigDTO;
import com.whfc.hdc.dto.FshTencentCloudUserSignDTO;
import com.whfc.hdc.dto.FshWarnRuleDTO;
import com.whfc.hdc.enums.FshCallType;
import com.whfc.hdc.enums.FshMediaSource;
import com.whfc.hdc.enums.FshMediaType;
import com.whfc.hdc.params.FshDeviceConfigParam;
import com.whfc.hdc.params.FshDeviceDataParam;
import com.whfc.hdc.params.FshDeviceMediaParam;
import com.whfc.hdc.params.FshEnterRoomParam;
import com.whfc.hdc.service.FshDeviceConfigService;
import com.whfc.hdc.service.FshDeviceDataService;
import com.whfc.hdc.service.FshDeviceMediaService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author qzexing
 * @version 1.0
 * @date 2021-04-06 17:47
 */
@Service
public class HdcFshOpenServiceImpl implements HdcFshOpenService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 腾讯云用户认证过期时间默认为1天
     */
    private static final Integer TENCENT_CLOUD_SIGN_EXPIRES = 24 * 3600;

    @Autowired
    private TrtcProperties trtcProps;

    @Autowired
    private JpushProperties jpushProps;

    @Autowired
    private FilePathConfig filePathConfig;

    @Autowired
    private FileHandler fileHandler;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @DubboReference(interfaceClass = FshDeviceConfigService.class, version = "1.0.0")
    private FshDeviceConfigService deviceConfigService;

    @DubboReference(interfaceClass = FshDeviceDataService.class, version = "1.0.0")
    private FshDeviceDataService deviceDataService;

    @DubboReference(interfaceClass = FshDeviceMediaService.class, version = "1.0.0")
    private FshDeviceMediaService deviceMediaService;

    @Override
    public FshTencentCloudUserSignDTO getTencentCloudUserSign(String sn) {
        TrtcApi signApi = new TrtcApi(trtcProps.getAppId(), trtcProps.getKey());
        String userSig = signApi.genUserSig(sn, TENCENT_CLOUD_SIGN_EXPIRES);
        return new FshTencentCloudUserSignDTO(userSig);
    }

    @Override
    public void enterRoom(String sn, FshEnterRoomParam param) {
        List<String> snList = param.getSnList();
        Integer type = param.getType();
        FshCallType callType = FshCallType.parseValue(type);
        if (callType == null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "通话类型不存在");
        }
        //获取极光推送注册ID
        List<String> registrationIdList = deviceConfigService.getRegistrationIdList(snList);
        if (registrationIdList == null || registrationIdList.isEmpty()) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "通话对象不存在");
        }
        //推送发起视频消息
        JPushApi jPushApi = new JPushApi(jpushProps.getAppKey(), jpushProps.getMasterSecret(), jpushProps.getApnsProduction(), JPushPlatform.ANDROID, JPushType.MESSAGE);
        JPushMessage message = new JPushMessage();
        message.setTitle(callType.getDesc());
        message.setContent(callType.getDesc());
        Map<String, String> extras = new HashMap<>();
        extras.put("strRoomId", sn);
        extras.put("type", type.toString());
        message.setExtras(extras);
        jPushApi.pushToDevices(registrationIdList, message);
    }

    @Override
    public FshDeviceConfigDTO getConfig(String sn) {
        return deviceConfigService.getDeviceConfig(sn);
    }

    @Override
    public void setConfig(FshDeviceConfigParam param) {
        deviceConfigService.setDeviceConfig(param);
    }


    @Override
    public void addCurrentData(FshDeviceDataParam param) {
        //发送广播 安全帽实时JSON数据
        String message = JSONUtil.toString(param);
        amqpTemplate.convertAndSend(QueueConst.FSH_CURRENT_DATA, message);
    }

    @Override
    public void pushRegister(Integer deviceId, String sn, String registrationId) {
        deviceConfigService.savePushRegistrationId(deviceId, sn, registrationId);
    }

    @Override
    public void saveMedia(Integer deviceId, String sn, Integer type, MultipartFile file) {
        FshMediaType mediaType = FshMediaType.parseValue(type);
        if (mediaType == null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "文件类型不存在");
        }
        //保存文件
        String filename = file.getOriginalFilename();
        String suffix = "";
        if (StringUtils.isNotBlank(filename)) {
            suffix = filename.substring(filename.lastIndexOf("."));
        }
        String filePath = filePathConfig.getFilePath("hdc/fsh/file");
        String fileName = RandomUtil.getRandomFileName() + suffix;
        String fileUrl;
        try {
            //文件上传
            InputStream inputStream = file.getInputStream();
            fileUrl = fileHandler.upload(filePath + "/" + fileName, inputStream);
        } catch (Exception e) {
            logger.warn("视频安全帽上传文件失败", e);
            return;
        }
        FshDeviceMediaParam params = new FshDeviceMediaParam();
        params.setDeviceId(deviceId);
        params.setSn(sn);
        params.setMediaType(type);
        params.setFileUrl(fileUrl);
        params.setSource(FshMediaSource.DEVICE.getValue());
        deviceMediaService.addDeviceMedia(params);
    }

    @Override
    public void updateNetState(Integer deviceId, String sn, Integer netState) {
        deviceDataService.updateNetState(deviceId, sn, netState);
    }

    @Override
    public List<FshWarnRuleDTO> getWarnTypeList() {
        return deviceConfigService.getWarnRuleList();
    }
}
